package com.py.custom.tms.application.atomic.array;

/**
 * description：
 *
 * @author pengyou
 * @version 1.0.0
 * @date 2022/4/7
 */
public class BinarySearch {


    public static void main(String[] args) {
        //  target = 2
        int[] nums = {-1, 0, 3, 5, 9, 9, 9, 12};
        int target = 9;
        System.out.println("search(nums, target) = " + search(nums, target));
        System.out.println("searchRight(nums, target) = " + searchRight(nums, target));
        System.out.println("searchLeft(nums, target) = " + searchLeft(nums, target));
    }


    /**
     * 二分查找
     *
     * @param nums
     * @param target
     * @return
     */
    public static int search(int[] nums, int target) {
        if (nums == null || nums[0] > target || nums[nums.length - 1] < target) {
            return -1;
        }
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            }
        }
        return -1;
    }

    /**
     * 二分查找最右侧
     *
     * @param nums
     * @param target
     * @return
     */
    public static int searchRight(int[] nums, int target) {
        if (nums == null || nums[0] > target || nums[nums.length - 1] < target) {
            return -1;
        }
        int left = 0;
        int right = nums.length;
        while (left < right) {
            int mid = (left + right) / 2;
            if (nums[mid] == target) {
                left = mid + 1;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid;
            }
        }
        if (left == 0) {
            return -1;
        }
        return nums[left - 1] == target ? (left - 1) : -1;
    }

    /**
     * 二分查找最左侧
     *
     * @param nums
     * @param target
     * @return
     */
    public static int searchLeft(int[] nums, int target) {
        if (nums == null || nums[0] > target || nums[nums.length - 1] < target) {
            return -1;
        }
        int left = 0;
        int right = nums.length;
        while (left < right) {
            int mid = (left + right) / 2;
            if (nums[mid] == target) {
                right = mid;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid;
            }
        }

        if (left == nums.length) {
            return -1;
        }
        return nums[left] == target ? left : -1;
    }
}
